/** 麦克风波形图 API*/
// import Index from '../../index'
/**
 * 传入一个录音波形数据的数组
 *  传入一个波形挂载的标签的Id
 * @param audioIndex  type 为'../../index'
 * @param elementId 
 */
const microphoneWaveformDiagram = (audioIndex:any,elementId:string)=>{
    let mountElement:HTMLElement = document.getElementById(elementId) as HTMLElement;
    let canvasElement:any;
    if(mountElement == null || mountElement.childNodes == null || mountElement.childNodes.length<=0){
        canvasElement = document.createElement("canvas");
    }else{
        canvasElement = mountElement.childNodes[0];
    }
    if(!mountElement) mountElement = document.getElementsByTagName("body").item(0)as HTMLElement;
    let ctx:CanvasRenderingContext2D = canvasElement.getContext("2d");
    const draw = ()=>{
        requestAnimationFrame(draw)
        // canvasElement.style.width='100%';
        // canvasElement.style.height='50%';
        //canvas宽高
        let canvasWidth = canvasElement.width;
        let canvasHeight = canvasElement.height;
        // console.log(canvasWidth,canvasHeight)
        //绘制canvas背景色以及形状
        ctx.fillStyle = "rgb(200,200,200)";
        ctx.fillRect(0,0,canvasWidth ,canvasHeight);
        //绘制波形形状以及颜色
        ctx.lineWidth = 2;//线宽
        ctx.strokeStyle = "rgb(0,0,0)";//线的颜色
        //判断是否正在录音
 
        if(!audioIndex.getRecorderStatus()) return;
        //通过上面的刷新 实时获取音频数据
        let dataArray = audioIndex.getRecordAnalyseData();
        //音频数据大小
        let bufferLength = dataArray.length;
        if(dataArray ==null || dataArray.length <=0) return;
        //开始绘制
        ctx.beginPath();
        //一个坐标点 占canvas多少位置
        let sliceWidth = canvasElement.width * 1.0 / bufferLength;
        //x轴
        let x = 0;
        for (let index = 0; index <bufferLength; index++) {
            let v = dataArray[index] / 128.0;
            let y = v * canvasHeight / 2;
            if(index === 0){
                //第一个坐标点
                ctx.moveTo(x,y);
            }else{
                //剩余坐标
                ctx.lineTo(x,y);
            }
            // 依次平移，绘制所有点
            x += sliceWidth;
        }
        ctx.lineTo(canvasElement.width,canvasElement.height/2);
        ctx.stroke();
    }
    mountElement.appendChild(canvasElement);
    draw();
    
}

export{microphoneWaveformDiagram}